import ReactDOM from 'react-dom/client';

export default function Loading({
  inline,
  size,
  lineWidth,
}: {
  inline?: boolean;
  size?: number;
  lineWidth?: number;
}) {
  return (
    <div
      className="loading-wrapper"
      style={
        inline
          ? {
              position: 'static',
              display: 'inline-block',
              verticalAlign: 'middle',
              width: 'auto',
            }
          : {}
      }
    >
      <div
        className="loading-animation loading-animation-style-4"
        style={inline ? { display: 'inline-block' } : {}}
      >
        <span
          className="loader"
          style={{
            ...(size ? { width: size, height: size } : {}),
            ...(lineWidth ? { borderWidth: lineWidth } : {}),
          }}
        ></span>
      </div>
    </div>
  );
}

let isLoading = false;
export function getLoadingControl() {
  let loadingDiv: any, loadingRoot: any;

  const openLoading = () => {
    if (isLoading) return;
    isLoading = true;

    loadingDiv = document.createElement('div');
    loadingDiv.setAttribute('id', 'loading-div');
    loadingRoot = ReactDOM.createRoot(loadingDiv);

    document.body.appendChild(loadingDiv);
    loadingRoot.render(<Loading />);
  };

  const closeLoading = () => {
    isLoading = false;
    loadingRoot?.unmount();
    const loadingDiv = document.getElementById('loading-div');
    loadingDiv && document.body?.removeChild?.(loadingDiv);
  };

  return {
    openLoading,
    closeLoading,
  };
}
